<template>
	<div class="cart">
    <TypeNav></TypeNav>
    <!-- 购物车列表 -->
    <div class="cart">
        <h4>全部商品</h4>
        <div class="cart-main">
            <!-- 购物车头部 -->
            <div class="cart-th">
              <div class="cart-th1">全部</div>
              <div class="cart-th2">商品</div>
              <div class="cart-th3">单价（元）</div>
              <div class="cart-th4">数量</div>
              <div class="cart-th5">小计（元）</div>
              <div class="cart-th6">操作</div>
            </div>

            <!-- 购物车内容 -->
            <div class="cart-body">
              <!-- 购物车列表内容 -->
              <!-- 若有商品 -->
              <template v-if='cartData.length'>
                <ul 
                  class="cart-list" 
                  v-for='item in cartData' 
                  :key='item.skuId'>
                    <!-- 勾选框 -->
                    <li class="cart-list-con1">
                      <input 
                        type="checkbox" 
                        name="chk_list" 
                        :checked='item.isChecked'
                        @click="checkedStatu(item.skuId,item.isChecked)"
                      >
                    </li>
                    <!-- 商品图片与商品名 -->
                    <li class="cart-list-con2">
                      <img :src='item.imgUrl'>
                      <div class="item-msg">{{item.skuName}}</div>
                    </li>
                    <!-- 商品介绍 -->
                    <li class="cart-list-con3">
                      <div class="item-txt">备注:(商品skuId：{{item.skuId}})</div>
                    </li>
                    <!-- 商品价格 -->
                    <li class="cart-list-con4">
                      <span class="price" style="color: red;font-size: 1rem">￥{{item.cartPrice.toFixed(2)}}</span>
                      <!-- <span class="price" >0.00</span> -->
                    </li>
                    <!-- 商品数量操作 -->
                    <li class="cart-list-con5">
                      <a href="javascript:void(0)" class="mins"  @click='decreaseGoodQuantity(item.skuNum,item.skuId)'>-</a>
                      <input
                        autocomplete="off"
                        type="text"
                        class="itxt"
                        :value='item.skuNum'
                        @change='inputGoodQuantity($event,item.skuNum,item.skuId,$event.target.value)'>
                      <a href="javascript:void(0)" class="plus"  @click='increaseGoodQuantity(item.skuId)'>+</a>
                    </li>
                    <!-- 商品小记 -->
                    <li class="cart-list-con6">
                      <span class="sum" style="color: red;font-size: 1rem">￥{{(item.cartPrice * item.skuNum).toFixed(2)}}</span>
                    </li>
                    <!-- 操作商品 -->
                    <li class="cart-list-con7">
                      <a 
                        href="javascript:" 
                        class="sindelet" 
                        style="margin:0;display: block;width:70px;height:;background-color: red;padding: 2px;color: #fff;text-align: center;border-radius: 10px;"
                        @click="deleteCommdity(item.skuId)"
                        >删除</a>
                      <br>
                      <a href="#none" style="margin: 0;display: block;width:70px;height:;background-color: #999;padding: 2px;color: #fff;text-align: center;border-radius: 10px;">移到收藏</a>
                    </li>
                </ul>
              </template>
              <!-- 若无商品 -->
              <ul class="cart-list" v-else>
                <li><h1>购物车暂无商品</h1></li>
              </ul>
              
            </div>
        </div>
        <!-- 购物车底部 -->
        <div class="cart-tool">
            <!-- 全选 -->
            <div class="select-all">
              <input 
                class="chooseAll" 
                type="checkbox" 
                :checked='isCheckedAll'
                :disabled='this.cartData.length?false:true'
                @change='allCheckedChange()'>
              <span>全选</span>
            </div>
            <!-- 操作 -->
            <div class="option">
              <a href="javascript:" @click='delCheckedCommodity()'>删除选中的商品</a>
              <a href="#none">移到我的关注</a>
              <a href="#none">清除下柜商品</a>
            </div>
            <!-- 信息 -->
            <div class="money-box">
              <div class="chosed">已选择
                  <span style="color:red;">{{checkTotal || 0}}</span>件商品</div>
              <div class="sumprice">
                  <em>总价（不含运费） ：</em>
                  <i class="summoney" style="color:red;">￥{{priceTotal || 0}}</i>
              </div>
              <div class="sumbtn">
                  <router-link class="sum-btn" to='/trade'>结算</router-link>
              </div>
            </div>
        </div>
    </div>
  </div>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
const {
  mapState:cartMapState,
  mapActions:cartMapActions
} = createNamespacedHelpers('cart')

import { addShopCart,delCartCommdity,checkedCartCommdity } from '@/api/api.js'

export default{
  mounted(){    
    this.getCartData()
  },
  data(){
    return {
      skuNum:''
    }
  },
  computed:{
    ...cartMapState(['cartData']),
    checkTotal(){
      return (this.cartData.filter(item => item.isChecked)).length
    },
    priceTotal(){
      let total = this.cartData.filter(item => item.isChecked)
      total = total.map( item => item.cartPrice * item.skuNum)
      return total.reduce((a,b)=>a+b,0)       
    },
    //页面初始加载全选判断
    isCheckedAll(){
      return this.cartData.every(item => item.isChecked)
      // console.log(this.cartData.every(item => item.isChecked))
    },
    //计算所有商品未被选中，存入数组，供全选商品方法使用
    uncheckedList(){
      return this.cartData.filter(item => !item.isChecked).map(item => item.skuId)
    },
    //所有商品已被选中计算，供全选商品,删除选中商品方法使用
    checkedList(){
      return this.cartData.filter(item => item.isChecked).map(item => item.skuId)
    }
  },
  methods:{
    ...cartMapActions(['getCartData','changeCommdityQuantity']),

    //减少商品数量
    async decreaseGoodQuantity(currentSkuNum,skuId){
      // 检查现有商品数量是否零
      console.log(currentSkuNum,skuId)
      if(currentSkuNum > 1){
        //请求api 操作商品数量
        const res = await addShopCart(skuId,-1)
        //重新发送请求，购物车信息
        this.getCartData()
        console.log(res.data.message)
      }else{
        const isDel = confirm('商品数量需大于零！，是否移除该商品？')
        if(isDel){
          this.deleteCommdity(skuId)
        }
      }
    },

    //增加商品数量
    async increaseGoodQuantity(skuId){
      //请求api 操作商品数量
      const res = await addShopCart(skuId,1)
      //重新发送请求，购物车信息
      this.getCartData()
      console.log(res.data.message)
    },

    //手动输入商品数量
    async inputGoodQuantity(e,currentSkuNum,skuId,inputSkuNum){
      // @currentSkuNum 为当前商品数量
      // @inputSkuNum 输入指定商品数量


      // 对当前的输入数量进行类型判断
      //排除字符串，undefined，NaN等非数字字符
      //排除小数,小于零的数
      if(isNaN(inputSkuNum) || inputSkuNum%1 !== 0 || inputSkuNum <= 0){  
          alert('请输入大于零的整数！')
          // 不满足还是重新赋值为原本的值
          e.target.value = currentSkuNum;
          // 不满足就停止执行函数，并退出
          return
      }

      // 和输入的数量进行对比
      // 分为两种情况： 当前>输入； 当前<输入；（无论如何输入都大于零）
      // 两种情况都可以用 请求 skuNum = 输入 - 当前
      let skuNum = inputSkuNum - currentSkuNum;

      //请求api 操作商品数量
      const res = await addShopCart(skuId,skuNum)
      // //重新发送请求，购物车信息
      this.getCartData()
      console.log(res.data.message)
    },
    //删除按钮--删除单一商品
    async deleteCommdity(skuId){
      const res = await delCartCommdity(skuId)
      this.getCartData()
      console.log('删除商品成功',res.data)
    },
    //选中状态改变
    async checkedStatu(skuId,isChecked){
      let statu = ''
      if(isChecked) statu = 0;
      else statu = 1;
      const res = await checkedCartCommdity(skuId,statu)
      this.getCartData()
    },
    // 全选商品-和-取消全选
    async allCheckedChange(){
      //此处是读取所有商品的 skuId并存为数组
      //@param-this.uncheckedList--计算属性：未被选中商品数组
      //@param-this.checkedList--计算属性：未被选中商品数组

      //---若所有商品均已选中---uncheckedList.lenght === 0      
      //若商品数据数组 长度为零，则不发请求
      if(!this.cartData.length) return

      //新建数组
      const reqArr=[]

      //若所有商品均已选中,则执行！！取消全选！！取消全选！！
      if(this.uncheckedList.length === 0){
        //将执行选中的异步网络请求函数存入数组
        this.checkedList.forEach(item =>{
          reqArr.push(checkedCartCommdity(item,0))
        })
      }
      //若所有商品均为选中,则执行！！全选全选！！全选全选！！
      else{
        //将执行选中的异步网络请求函数存入数组
        this.uncheckedList.forEach(item =>{
          reqArr.push(checkedCartCommdity(item,1))
        })
      }

      //!!!! Promise.all !!!! 调用存储了选中函数-数组
      await Promise.all(reqArr)
      // .then((res)=>{console.log('ok')})

      //重新请求购物车信息
      this.getCartData()
    },

    //删除选中商品--批量
    async delCheckedCommodity(){
      //原理 全选，全选取消相同
      if(this.checkedList.length===0) return

      const reqArr = []
      this.checkedList.forEach(item=>{
         reqArr.push(delCartCommdity(item))
      })

      await Promise.all(reqArr).then((res)=>{console.log('ok')})

      this.getCartData()
    }
  }
}
</script>

<style lang="scss" scoped>
.cart{
    width: 1200px;
    margin: 0 auto;
    h4{
        margin: 9px 0;
        font-size: 14px;
        line-height: 21px;
    }
    .cart-main{
        .cart-th{
            background: #f5f5f5;
            border: 1px solid #ddd;
            padding: 10px;
            overflow: hidden;
            &>div{
                float: left;
            }
            .cart-th1{
                width: 25%;
                input{
                    vertical-align: middle;
                }
                span{
                    vertical-align: middle;
                }
            }
            .cart-th2{
                width: 25%;
            }
            .cart-th3,.cart-th4,.cart-th5,.cart-th6{
                width: 12.5%;

            }
        }
        .cart-body{
            margin: 15px 0;
            border: 1px solid #ddd;
            .cart-list{
                padding: 10px;
                border-bottom: 1px solid #ddd;
                overflow: hidden;
                &>li{
                    float: left;
                }
                .cart-list-con1{
                    width: 4.1667%;
                }
                .cart-list-con2{
                    width: 25%;
                    img{
                        width: 82px;
                        height: 82px;
                        float: left;
                    }
                    .item-msg{
                        float: left;
                        width: 150px;
                        margin: 0 10px;
                        line-height: 18px;
                    }
                }
                .cart-list-con3{
                    width: 20.8333%;
                    .item-txt{
                        text-align: center;
                    }
                }
                .cart-list-con4{
                    width: 12.5%;

                }
                .cart-list-con5{
                    width: 12.5%;
                    .mins{
                        border: 1px solid #ddd;
                        border-right: 0;
                        float: left;
                        color: #666;
                        width: 6px;
                        text-align: center;
                        padding: 8px;
                    }
                    input{
                        border: 1px solid #ddd;
                        width: 40px;
                        height: 33px;
                        float: left;
                        text-align: center;
                        font-size: 14px;
                    }
                    .plus{
                        border: 1px solid #ddd;
                        border-left: 0;
                        float: left;
                        color: #666;
                        width: 6px;
                        text-align: center;
                        padding: 8px;
                    }
                }
                .cart-list-con6{
                    width: 12.5%;
                    .sum{
                        font-size: 16px;
                    }
                }
                .cart-list-con7{
                    width: 12.5%;
                    a{
                        color: #666;
                    }
                }
            }
        }
    }
    .cart-tool{
        overflow: hidden;
        border: 1px solid #ddd;
        .select-all{
            padding: 10px;
            overflow: hidden;
            float: left;
            span{
                vertical-align: middle;
            }
            input{
                vertical-align: middle;
            }
        }
        .option{
            padding: 10px;
            overflow: hidden;
            float: left;
            a{
                float: left;
                padding: 0 10px;
                color: #666;
            }
        }
        .money-box{
            float: right;
            .chosed{
                line-height: 26px;
                float: left;
                padding: 0 10px;
            }
            .sumprice{
                width: 200px;
                line-height: 22px;
                float: left;
                padding: 0 10px;
                .summoney{
                    color: #c81623;
                    font-size: 16px;
                }
            }
            .sumbtn{
                float: right;
                a{
                    display: block;
                    position: relative;
                    width: 96px;
                    height: 52px;
                    line-height: 52px;
                    color: #fff;
                    text-align: center;
                    font-size: 18px;
                    font-family: "Microsoft YaHei";
                    background: #e1251b;
                    overflow: hidden;
                }
            }
        }
    }
}
</style>
